package usr;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import page.PageState;
import channel.ChannelMail;

public class UsrSendPassword extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Usr usr = new Usr();
		usr.setEmail(req.getParameter("email"));
		
		int i = usr.getEmail().indexOf('@');
		int j = usr.getEmail().indexOf('.', i);
		
		if ( i < 0 || j < 0 || j - i < 2 ) {
			req.setAttribute("error_cause", PageState.NOT_AN_EMAIL);
			req.getRequestDispatcher("forgetPassword.jsp").forward(req, resp);
			
		} else {
			i = usr.getUsrByEmail();
			if ( i != PageState.SUCCESSFUL ) {
				req.setAttribute("error_cause", i);
				req.getRequestDispatcher("forgetPassword.jsp").forward(req, resp);
				
			} else {
				ChannelMail mail = new ChannelMail();
				mail.setSubject("njucs-ifttt password");
				mail.setBody(
					"Your Password of Account " + usr.getLogin() + 
					" on njucs-ifttt is " + usr.getPassword() + ".\n");
				mail.setTo(usr.getEmail());
				mail.THAT();
				
				req.setAttribute("error_cause", i);
				req.getRequestDispatcher("forgetPassword.jsp").forward(req, resp);
			}
		}
		
	}
}
